package liwen.zhao.controller;

import liwen.zhao.common.jd.pojo.CommonUser;
import liwen.zhao.common.jd.utils.CookieUtils;

import liwen.zhao.common.jd.vo.SysResult;
import liwen.zhao.service.UserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RestController
@RequestMapping("/user")
public class AdminUserController {
    @Autowired
    UserService userService;
    @Autowired
    SysResult sysResult;
    
    @RequestMapping("/CommonUserTest")
    public CommonUser CommonUserTest(String userName) {
        return userService.findCommonUserByName(userName);
    }
    
    @RequestMapping("/adminLogin")
    public SysResult adminLogin(@Param("userName") String userName, @Param("psw") String psw, @Param("valicode") String valicode, @Param("rember")boolean rember,HttpServletRequest request, HttpServletResponse response) {
        if (null == valicode || valicode.equals("")) {
            sysResult = SysResult.build(500, "验证码不能为空", null);
            return sysResult;
        }
        String valiCodeId = CookieUtils.getCookieValue(request, "valiCodeId");
        String savedValiCode = userService.getValiCode(valiCodeId);
        if (!valicode.equalsIgnoreCase(savedValiCode)) {
            sysResult = SysResult.build(500, "验证码有误", null);
            return sysResult;
        }
        sysResult = userService.adminLogin(userName, psw, "user/adminLogin");
        if (sysResult.getStatus() == 200) {
            String cookiek = (String) sysResult.getData();
            CookieUtils.setCookie(request, response, "commonUser", cookiek);
            
            if(rember){
                CookieUtils.setCookie(request, response, "userName",userName,60*60*24*30);
            }else{
                CookieUtils.setCookie(request, response, "userName","",0);
            }
        }
        return sysResult;
    }
    
   
}
